#!/usr/bin/env python
# -*- coding: utf-8 -*-

# #portugues@ScoutLink 2006 JOTI Bot (slbot)
# Copyright (c) 2006, ScoutLink #portugues team
# This source is released under the New BSD License. See the LICENSE file for further
# information.

# $Author: fmobus $
# $Date: 2006-09-20 19:26:49 +0000 (Wed, 20 Sep 2006) $ 

"""SLBot init script. Calls functions to parse the configuration file
(provided as a command line argument), initializes the twisted library
and "kickstarts" the bot.

"""

__version__ = "$Revision: 23 $"
# $Source$

import os
import sys
import ConfigParser
import time

import twisted.python
import twisted.internet

import slbot.slbotfactory
import slbot.slbot
import slbot.slconfig

if __name__ == "__main__":
    # Loads configuration file from command line parameter
    if len(sys.argv) == 1:
        sys.stderr.write("You should provide a config file.\n")
        sys.exit()

    try:
        config = slbot.slconfig.SLConfig()
        config.read(sys.argv[1])
    except ConfigParser.MissingSectionHeaderError:
        sys.stderr.write("You should provide a _valid_ config file.\n")
        sys.exit()

    # Start double-fork technique to properly detach from calling terminal
    try:
        pid = os.fork()
        if pid > 0:         # Exit first parent
            print 'fork #1 done'
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, 'fork #1 failed: %d (%s)' % (e.errno, e.strerror)
        sys.exit(1)

    # Open any needed file before chdir'ing to '/'
    pidfile = file('%s.pid' % (config.get('main','nickname'),),"w")
    os.chdir("/")
    os.setsid()
    os.umask(0)

    try:
        pid = os.fork()
        if pid > 0:         # Exit second parent, dumping pid
            print 'Process gone into background (pid: %d)' % (pid,)
            pidfile.write("%d\n" % (pid,))
            pidfile.close()
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, 'fork #2 failed: %d (%s)' % (e.errno, e.strerror)
        sys.exit(1)

    # we are good to go =)
    twisted.python.threadable.init()
    f = slbot.slbotfactory.SLBotFactory(config)
    twisted.internet.reactor.connectTCP(config.get('main', 'server'), 6667, f)
    twisted.internet.reactor.run()
